<script setup>
import {ref, reactive, onMounted, onUnmounted} from 'vue'
import * as echarts from 'echarts';
import axios from 'axios';

const form = reactive({
  name: '',
  file: '',
  myFile: ''
})

let myChart = reactive(null);
let timer = null;
let diskDataCache = null; // 缓存初始的磁盘数据
let currentOption = null; // 保存当前图表配置
let option = ref(null);
let start, end;


const onSubmit = () => {
  console.log('submit!')
}

onMounted(() => {
  initEcharts()

  //监听鼠标滚轮

});

onUnmounted(() => {
  if (timer) {
    clearInterval(timer);
  }
  if (myChart) {
    myChart.dispose();
  }
});

// 修改更新函数，只更新必要的数据
const updateChartData = async () => {
  try {
    const percentageData = await axios.get('http://localhost:2000/data1.json');

    // 获取当前的系列数据
    const currentSeriesData = myChart.getOption().series[0].data;


    // 只更新百分比和颜色，保持其他属性不变
    function updateNodeData(nodes) {
      return nodes.map(node => {
        const newNode = {...node}; // 创建节点的副本
        if (newNode.children) {
          newNode.children = updateNodeData(newNode.children);
          // 更新父节点的边框颜色
          if (newNode.children.length > 0) {
            newNode.itemStyle = {
              borderColor: newNode.children[0].itemStyle.color
            };
          }
        } else if (newNode.code) {
          const percentage = getPercentage(newNode.code, percentageData.data);
          if (percentage !== null) {
            newNode.percentage = percentage;
            newNode.itemStyle = {
              color: getColor(percentage)
            };
          }
        }
        return newNode;
      });
    }

    // 更新数据但保持结构不变
    const updatedData = updateNodeData(currentSeriesData);

    // myChart.setOption({
    //   series: [{
    //     data: updatedData
    //   }]
    // },true);
    // option.series[0].data = updatedData;
    console.log(myChart.getOption().dataZoom);
    option.value.series[0].data = updatedData;
    myChart.setOption({
      series: [{
        data: updatedData
      }]
    }, {
      notMerge: false,
      lazyUpdate: true,
      silent: true
    });
    //   series: {
    //     data: updatedData
    //   }
    // });
  } catch (error) {
    console.error('Failed to update data:', error);
  }
};

const initEcharts = async () => {
  var chartDom = document.getElementById('main');
  myChart = echarts.init(chartDom, null, {
    useDirtyRect: true
  });
  myChart.showLoading();
  try {
    const [diskData, percentageData] = await Promise.all([
      axios.get('http://localhost:2000/echarts.json'),
      axios.get('http://localhost:2000/data.json')
    ]);

    diskDataCache = diskData.data.children;
    myChart.hideLoading();

    function getLevelOption() {
      return [
        {
          itemStyle: {
            gapWidth: 1
          },
          upperLabel: {
            show: false
          }
        },
        {
          itemStyle: {
            borderColor: '#000',
            borderWidth: 2,
          },
        },
        {
          itemStyle: {
            borderColor: '#000',
            borderWidth: 1,
            gapWidth: 0,
            borderColorSaturation: 0.5
          },
          emphasis: {
            itemStyle: {
              borderColor: '#FED514'
            }
          }
        },
        {
          color: [], //颜色 
          itemStyle: {
            borderColor: '#000',
            borderWidth: 0.5,
            gapWidth: 0,
          },
          emphasis: {
            itemStyle: {
              borderColor: '#FED514'
            }
          }
        },
      ];
    }

    option.value = {
      tyepe: 'treemap',
      title: {
        text: '大盘云图',
        left: 'center'
      },
      tooltip: {
        borderColor: '#000',
        borderWidth: 2,
        padding: 0,
        position: function (point, params, dom, rect, size) {
          return [point[0], '2%'];
        },
        formatter: function (params) {
          if (params.treeAncestors.length <= 2) {
            return;
          }
          const parentNode = params.treeAncestors[params.treeAncestors.length - 2].data;

          const childrenSection = params.data.children?.map((child, index) => {
            if (index === 0) {
              return `
              <div class="tooltip-title" 
                style="background-color:${params.borderColor}"
                >
                ${child.name} ${child.percentage}%
             </div>
                `;
            }
            return `<div class="tooltip-text">${child.name}${child.percentage}%</div>`
          }).join('');
          return [childrenSection]
              .filter(Boolean)
              .join('');
        }
      },
      series: [
        {
          name: 'Disk Usage',
          type: 'treemap',
          width: '100%',
          height: '90%',
          // sampling: 'average',//' 表示采用平均值采样策略
          // large: true,
          // largeThreshold: 100,
          roam: 'scale',
          scaleLimit: {
            min: 1,
            max: 2
          },
          nodeClick: false,
          label: {
            show: true,
            align: 'center',
            verticalAlign: 'center',
            fontSize: 10,
            fontStyle: 'italic',
            formatter: function (params) {
              if (!params.data.children && params.data.percentage !== undefined) {
                return `${params.name}\n${params.data.percentage}%`;
              }
              return params.name;
            }
          },
          itemStyle: {
            borderColor: '#fff',
            gapWidth: 5
          },
          upperLabel: {
            show: true,
            height: 20,
            color: '#fff'
          },
          levels: getLevelOption(),
          data: processTreemapData(diskData.data.children, percentageData.data)
        }
      ]
    };

    currentOption = option.value;
    myChart.setOption(option.value);

    // 设置定时器，每15秒更新一次数据
    timer = setInterval(updateChartData, 3000);

  } catch (error) {
    console.error('Failed to initialize chart:', error);
    myChart.hideLoading();
  }
};

// 辅助函数保持不变
const getPercentage = (code, percentageData) => {
  if (!code || !percentageData[code]) return null;
  const value = percentageData[code].split('|')[1];
  return parseFloat(value);
};

const processTreemapData = (data, percentageData) => {
  function transformNode(node, level = 0) {
    const result = {
      name: node.name,
      code: node.code,
      value: node.scale
    };

    if (node.children && node.children.length > 0) {
      result.children = node.children.map(child => transformNode(child, level + 1));
      result.itemStyle = {
        borderColor: result.children[0].itemStyle.color
      }
    } else if (node.code) {
      const percentage = getPercentage(node.code, percentageData);
      if (percentage !== null) {
        result.percentage = percentage;
        result.itemStyle = {
          color: getColor(percentage)
        };
      }
    }

    return result;
  }

  return data.map(item => ({
    name: item.name,
    children: item.children ? item.children.map(child => transformNode(child, 0)) : undefined
  }));
};

const getColor = (percentage) => {
  const colorMap = [
    {range: '>=4', color: '#e41813'},
    {range: '>=3', color: '#be1207'},
    {range: '>=2', color: '#960f0f'},
    {range: '>=1', color: '#6d1414'},
    {range: '<=-4', color: '#28d742'},
    {range: '<=-3', color: '#1da548'},
    {range: '<=-2', color: '#106f2f'},
    {range: '<=-1', color: '#0a5421'},
    {range: 'default', color: '#424454'}
  ];

  for (const item of colorMap) {
    if ((item.range === '>=4' && percentage >= 4) ||
        (item.range === '>=3' && percentage >= 3) ||
        (item.range === '>=2' && percentage >= 2) ||
        (item.range === '>=1' && percentage >= 1) ||
        (item.range === '<=-4' && percentage <= -4) ||
        (item.range === '<=-3' && percentage <= -3) ||
        (item.range === '<=-2' && percentage <= -2) ||
        (item.range === '<=-1' && percentage <= -1) ||
        (item.range === 'default')) {
      return item.color;
    }
  }
};
</script>

<template>
  <div id="main" style="width: 90vw; height: 90vh;"></div>
  <el-button style="background-color: #28d742;">-4%</el-button>
  <el-button style="background-color: #1da548;">-3%</el-button>
  <el-button style="background-color: #106f2f;">-2%</el-button>
  <el-button style="background-color: #0a5421;">-1%</el-button>
  <el-button style="background-color: #424454;">0%</el-button>
  <el-button style="background-color: #6d1414;">1%</el-button>
  <el-button style="background-color: #960f0f;">2%</el-button>
  <el-button style="background-color: #be1207;">3%</el-button>
  <el-button style="background-color: #e41813;">4%</el-button>
</template>

<style lang="scss">
.tooltip-title {
  width: 180px;
  padding: 10px 0;
  color: white;
}
</style>